package com.bawan.utils;

import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;


/**
 * Desc:  利用javamail发送邮件的工具类
 * Author: zhengcongchun
 * CreateTime: 2014-03-05 11:16
 * LastModifyTime: 2014-03-05 11:16
 * FinalModifier: zhengcongchun
 * Version: 1.0
 */
public class SendMailUtil {
    private String mailTo;
    private String mailFrom;
    private String mailHost;
    private String username;
    private String password;
    private String filename;
    private String subject;
    private String content;
    private Vector files = new Vector();

    public static String str_encode = "GB2312";

    /**
     * 默认构造器
     */
    public SendMailUtil() {
    }

    /**
     * 构造器: 可直接传入参数
     *
     * @param mailTo
     * @param mailFrom
     * @param mailHost
     * @param username
     * @param password
     * @param filename
     * @param subject
     * @param content
     */
    public SendMailUtil(String mailTo, String mailFrom, String mailHost,
                        String username, String password, String filename,
                        String subject, String content) {
        this.mailTo = mailTo;
        this.mailFrom = mailFrom;
        this.mailHost = mailHost;
        this.username = username;
        this.password = password;
        this.filename = filename;
        this.subject = subject;
        this.content = content;
    }

    /**
     * 将字符串转成中文
     *
     * @param text
     * @return
     */
    public String transferChinese(String text) {
        try {
            text = MimeUtility.encodeText(new String(text.getBytes(), str_encode), str_encode, "B");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return text;
    }

    /**
     * 添加附件到附件集合中
     *
     * @param fname
     */
    public void attachfile(String fname) {
        files.addElement(fname);
    }

    public boolean sendMail() {
        //构造 mail session
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        try {
            //构造 MimeMessage 并设定基本的值
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(mailFrom));
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));

            //添加邮件主题
            msg.setSubject(subject, "UTF-8");

            // 构造Multipart
            Multipart mp = new MimeMultipart();

            // 向Multipart添加正文
            MimeBodyPart mbpContent = new MimeBodyPart();
            mbpContent.setContent(content, "text/html;charset=UTF-8");

            // 向MimeMessage添加（Multipart代表正文）
            mp.addBodyPart(mbpContent);

            //添加附件
            if (!files.isEmpty()) {//有附件
                Enumeration efile = files.elements();
                while (efile.hasMoreElements()) {
                    mbpContent = new MimeBodyPart();
                    filename = efile.nextElement().toString(); //选择出每一个附件名
                    FileDataSource fds = new FileDataSource(filename); //得到数据源
                    mbpContent.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart
                    mbpContent.setFileName(MimeUtility.encodeText(fds.getName(), "GBK", "B"));  //得到文件名同样至入BodyPart
                    mp.addBodyPart(mbpContent);
                }
                files.removeAllElements();
            }

            msg.setContent(mp);
            msg.setSentDate(new Date());
            msg.saveChanges();

            // 发送邮件
            Transport transport = session.getTransport("smtp");
            transport.connect(mailHost, username, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } catch (Exception mex) {
            mex.printStackTrace();
            return false;
        }
        return true;
    }

    public String getMailTo() {
        return mailTo;
    }

    /**
     * 设置邮件发送目的邮箱
     * @param mailTo
     */
    public void setMailTo(String mailTo) {
        this.mailTo = mailTo;
    }

    public String getMailFrom() {
        return mailFrom;
    }

    /**
     * 设置邮箱发送源邮箱
     * @param mailFrom
     */
    public void setMailFrom(String mailFrom) {
        this.mailFrom = mailFrom;
    }

    public String getMailHost() {
        return mailHost;
    }

    /**
     * 设置邮件发送服务器
     * @param mailHost
     */
    public void setMailHost(String mailHost) {
        this.mailHost = mailHost;
    }

    public String getUsername() {
        return username;
    }

    /**
     * 设置登陆发送服务器的检验用户名
     * @param username
     */
    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    /**
     * 设置登陆发送服务器的检验密码
     * @param password
     */
    public void setPassword(String password) {
        this.password = password;
    }

    public String getFilename() {
        return filename;
    }

    /**
     * 设置发送邮件的附件名
     * @return
     */
    public void setFilename(String filename) {
        this.filename = filename;
    }

    public String getSubject() {
        return subject;
    }

    /**
     * 设置发送邮件的主题
     * @param subject
     */
    public void setSubject(String subject) {
        this.subject = transferChinese(subject);
    }

    public String getContent() {
        return content;
    }

    /**
     * 设置邮件发送的内容
     * @param content
     */
    public void setContent(String content) {
        this.content = transferChinese(content);
    }
}
